package cn.cj.erp.serviceimpl.system;

import cn.cj.erp.common.utils.Convert;
import cn.cj.erp.dao.system.SysRoleDeptDao;
import cn.cj.erp.bo.system.SysRoleDeptBo;
import cn.cj.erp.service.system.SysRoleDeptService;
import cn.cj.erp.serviceimpl.base.ServiceImpl;
import cn.hutool.core.collection.CollectionUtil;
import cn.cj.erp.entity.system.SysRoleDept;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * 角色与部门对应关系
 *
 * @author chenjian
 */
@Slf4j
@Service
public class SysRoleDeptServiceImpl extends ServiceImpl<SysRoleDept, SysRoleDeptBo>
        implements SysRoleDeptService {
    @Resource
    private SysRoleDeptDao sysRoleDeptDao;

    @Override
    public SysRoleDeptDao getBaseMapper() {
        return sysRoleDeptDao;
    }

    @Override
    public SysRoleDept convert2Entity(SysRoleDeptBo sysRoleDeptBo) {
        return Convert.convert(sysRoleDeptBo, SysRoleDept.class);
    }

    @Override
    public SysRoleDeptBo convert2Bo(SysRoleDept sysRoleDept) {
        return Convert.convert(sysRoleDept, SysRoleDeptBo.class);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveAllDeptToRole(Long roleId, List<Long> deptIds) {
        //先删除角色与部门关系
        this.removeByRoleId(roleId);
        if (CollectionUtil.isEmpty(deptIds)) {
            log.info("没有需要处理的角色部门，直接返回成功");
            return true;
        }
        //保存角色与菜单关系
        List<SysRoleDeptBo> list = SysRoleDeptBo.newList(roleId, deptIds);
        boolean result = super.saveBatch(list);
        if (!result) {
            log.error("批量保存数据失败，打上回滚标记");
            // 批量保存失败，需要回滚
            rollback();
            return false;
        }
        return true;
    }

    @Override
    public List<Long> listDeptIdsByRoleIds(List<Long> roleIds) {
        return getBaseMapper().listDeptIdByRoleIds(roleIds);
    }

    @Override
    public boolean removeByRoleId(Long roleId) {
        return lambdaUpdate()
                .eq(SysRoleDept::getRoleId, roleId)
                .remove();
    }

    @Override
    public boolean removeByRoleIds(List<Long> roleIds) {
        if (CollectionUtil.isEmpty(roleIds)) {
            log.info("没有需要删除的数据，直接返回成功");
            return true;
        }
        return lambdaUpdate()
                .in(SysRoleDept::getRoleId, roleIds)
                .remove();
    }
}
